#include "mainwindow.h"
#include "ui_mainwindow.h"

//float regTable[90][2]={
//    {0.1, 0},
//    {0.2, 1},
//    {0.3, 2}//自行填充至90度（{xx，90}）
//};

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    server = new QTcpServer();
    server->listen(QHostAddress::Any, PORT);
    connect(server, SIGNAL(newConnection()), this, SLOT(NewConnSlot()));
    view1 = new QWebEngineView(this);
    view2 = new QWebEngineView(this);
    view1->close();
    view2->close();

    ui->radioButtonBothCh->setChecked(true);
    ui->labelBothNoSignal->close();
}

MainWindow::~MainWindow()
{
    server->close();
    view1->close();
    view2->close();
    delete ui;
}

void MainWindow::NewConnSlot()
{
    currentClient = server->nextPendingConnection();
    tcpClient.append(currentClient);
    CameraData camDataTmp;
    SocketInfo socketInfo;
    qDebug() << "new Tcp client ip:" << currentClient->peerAddress().toString().split("::ffff:")[1] << endl;
    QString ip = currentClient->peerAddress().toString().split("::ffff:")[1].replace(QRegExp("%10$"), "");
    qDebug()<<ip;
    socketInfo.url = "http://" + ip + ":8000";
    camDataTmp.length = 0;
    camDataTmp.distance = 0;
    qDebug() << "new Tcp client :" << socketInfo.url << endl;
    socketInfo.camData = camDataTmp;
    socketInfo_.push_back(socketInfo);
    connect(currentClient, SIGNAL(readyRead()), this, SLOT(ReadData()));
    connect(currentClient, SIGNAL(disconnected()), this, SLOT(disconnectedSlot()));
}

void MainWindow::disconnectedSlot()
{
    QString url;
    for(int i=0; i<tcpClient.length(); i++)
    {
        if(tcpClient[i]->state() == QAbstractSocket::UnconnectedState)
        {
            // 删除存储在tcpClient列表中的客户端信息
            url = tcpClient[i]->peerAddress().toString();
            tcpClient[i]->destroyed();
            tcpClient.removeAt(i);
        }
    }
    qDebug() << "client " << url << "disconnected" << endl;
    for(int i=0; i<socketInfo_.size(); i++)
    {
        if(url.indexOf(socketInfo_.at(i).url.toString()))
        {
            socketInfo_.erase(socketInfo_.begin()+i);
        }
    }
}

void MainWindow::ReadData()
{
    // 由于readyRead信号并未提供SocketDecriptor，所以需要遍历所有客户端
    for(int i=0; i<tcpClient.length(); i++)
    {
        if (i > 1) break;
        QByteArray buffer = tcpClient[i]->readAll();
        if(buffer.isEmpty())    continue;
        qDebug() << "rec from " << tcpClient[i]->peerAddress().toString() << ",data:" << buffer << endl;
        cJSON *json = cJSON_Parse(buffer);
        if(!json) continue;
        cJSON *len = cJSON_GetObjectItem(json, "Length");
        cJSON *dis = cJSON_GetObjectItem(json, "Distance");
        if (!len || !dis) continue;
        int lengthTmp = len->valueint, disTmp = dis->valueint;
        if (lengthTmp >= 50 && lengthTmp <= 150)
            socketInfo_.at(i).camData.length = lengthTmp;
        else
            socketInfo_.at(i).camData.length = socketInfo_.at(1-i).camData.length;
        socketInfo_.at(i).camData.distance = disTmp;
        socketInfo_.at(i).camData.isRecd = true;
        if(json) cJSON_Delete(json);
    }
    ProcessData();
}

void MainWindow::resizeEvent(QResizeEvent *)
{
    //    view1->resize(this->size().width()/2, this->size().height());
    //    view2->resize(this->size().width()/2, this->size().height());
    //    view1->move(0,70);
    //    view2->move(this->size().width()/2,70);
}

void MainWindow::CloseAllView()
{
    view1->close();
    view2->close();
    ui->labelBothNoSignal->close();
    ui->labelFirstNoSignal->close();
    ui->labelSecondNoSignal->close();
}

void MainWindow::on_radioButtonFirstCh_clicked()
{
    CloseAllView();
    if (socketInfo_.size() >= 1)
    {
        view1->load(socketInfo_.at(0).url);
        view1->show();
        view1->resize(this->size().width(), this->size().height() - 70);
        view1->move(0,70);
    }
    else
        ui->labelBothNoSignal->show();
}


void MainWindow::on_radioButtonSecondCh_clicked()
{
    CloseAllView();
    if (socketInfo_.size() >= 2)
    {
        view2->load(socketInfo_.at(1).url);
        view2->show();
        view2->resize(this->size().width(), this->size().height() - 70);
        view2->move(0,70);
    }
    else
        ui->labelBothNoSignal->show();
}
void MainWindow::on_radioButtonBothCh_clicked()
{
    CloseAllView();
    if (socketInfo_.size() >= 1)
    {
        view1->load(socketInfo_.at(0).url);
        view1->show();
        view1->resize(this->size().width()/2, this->size().height() - 70);
        view1->move(0,70);
    }
    else
        ui->labelFirstNoSignal->show();
    if (socketInfo_.size() >= 2)
    {
        view2->load(socketInfo_.at(1).url);
        view2->show();
        view2->resize(this->size().width()/2, this->size().height() - 70);
        view2->move(this->size().width()/2,70);
    }
    else
        ui->labelSecondNoSignal->show();
}

void MainWindow::RefreshAllView()
{
    if (ui->radioButtonBothCh->isChecked())
        on_radioButtonBothCh_clicked();
    else if (ui->radioButtonFirstCh->isChecked())
        on_radioButtonFirstCh_clicked();
    else if (ui->radioButtonSecondCh->isChecked())
        on_radioButtonSecondCh_clicked();
}

void MainWindow::ProcessData()
{
#ifdef MULTICHANNELS
    int len, reg;
    if (socketInfo_.size() < 2) return;
    if (socketInfo_.at(0).camData.distance > socketInfo_.at(1).camData.distance)
        len = socketInfo_.at(0).camData.length;
    else len = socketInfo_.at(1).camData.length;
#else
    int len = 0;
    for (int i=0; i<socketInfo_.size(); i++) {
        len += socketInfo_.at(i).camData.length;
    }
    len = len/socketInfo_.size();
#endif

#ifdef USE_REG_TABLE
    float dataValue = (float)socketInfo_.at(0).camData.distance / socketInfo_.at(1).camData.distance;
//  填充regTable后才可以索引出角度值
    float dataTmp = dataValue - regTable[0][0];
    for (int i = 0; i < 90; i++) {
        float tmp = dataValue - regTable[i][0];
        if (tmp < dataTmp)
        {
            dataTmp = tmp;
            reg = regTable[i][1];
        }
    }
#else
    qreal tanValue = atan2(socketInfo_.at(0).camData.distance, socketInfo_.at(1).camData.distance);
    reg = tanValue * 180 / 3.1415;
#endif
    if (socketInfo_.at(0).camData.isRecd && socketInfo_.at(1).camData.isRecd)
    {
        qDebug() << "Length: " << len << "Reg:" << reg << endl;
        ui->labelLength->setText(QString("长度L：") + QString::number(len) + QString("cm"));
        ui->labelLength->setText(QString("角度Reg：") + QString::number(reg));
    }
}

void MainWindow::ForceFinishMeau()
{
    socketInfo_.at(0).camData.isRecd = true;
    socketInfo_.at(1).camData.isRecd = true;
}

void MainWindow::on_pushButton_clicked()
{
    for (int i=0; i<tcpClient.length(); i++) {
        tcpClient[i]->write("{\"cmd\":\"start\"}");
    }
    QElapsedTimer t;
    t.start();
    while(t.elapsed()<3000)
        QCoreApplication::processEvents();
    RefreshAllView();

    QElapsedTimer t1;
    t1.start();
    while(t1.elapsed()<200000)
        QCoreApplication::processEvents();
    if (socketInfo_.at(0).camData.isRecd == false || socketInfo_.at(1).camData.isRecd == false)
    {
        ForceFinishMeau();
        ProcessData();
    }
}
